//
//  XDQiniuManager.m
//  kabu
//
//  Created by XiangDongMBP on 2017/2/28.
//  Copyright © 2017年 East. All rights reserved.
//

#import "XDQiniuManager.h"
#import <QiniuSDK.h>
#import "EFAModel.h"
#import "XDAFNetworking.h"
#import "ApiManager.h"
#import "GlobalHeader.h"

@interface XDQiniuManager ()

@property (nonatomic, copy) XDQNUpProgressHandler prohander;
@property (nonatomic, copy) XDQNUpSuccessHandler sucHander;
@property (nonatomic, copy) XDQNUpFailureHandler faiHander;

@property (nonatomic, strong) QNUploadManager *qnUpManager;
@property (nonatomic, assign) BOOL cancelUploadFlag;
@property (nonatomic, assign) BOOL isUploading;     //防止一次上传任务还没有完成，又开始新的上传任务，导致出错
@property (nonatomic, copy)   NSString *qnUpToken;

@end

@implementation XDQiniuManager

+ (instancetype)sharedInstance {
    static XDQiniuManager * sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

- (void)cancelUpload {
    self.cancelUploadFlag = YES;
}

- (void)uploadImages:(NSArray<UIImage *> *)imgArray progress:(XDQNUpProgressHandler)progress success:(XDQNUpSuccessHandler)success failure:(XDQNUpFailureHandler)failure {
    // 校验参数
    if (!imgArray.count) {
        if (failure) {
            failure(@"上传图片数组为空");
        }
        return;
    }
    
    // 判断是否真正上传
    if (self.isUploading) {
        NSLog(@"还有未完成的上传任务");
        if (failure) {
            failure(@"还有未完成的上传任务");
        }
        return;
    }
    
    NSMutableArray<NSData *> *mDataArray = [NSMutableArray arrayWithCapacity:imgArray.count];
    [imgArray enumerateObjectsUsingBlock:^(UIImage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSData *data = UIImageJPEGRepresentation(obj, 1);
        if (data) {
            [mDataArray addObject:data];
        }
    }];
    
    // 获取上传的Token
    [self getQiniuUploadToken:^(NSString *token) {
        self.qnUpToken = token;
        [self subUploadImgData:mDataArray progress:progress success:success failure:failure];
    } failure:^(NSString *error) {
        if (failure) {
            failure(error);
        }
    }];
    
//    // 开始上传
//    self.isUploading = YES;
//    
//    // 取消上传重置为NO
//    self.cancelUploadFlag = NO;
//    
//    // 上传图片
//    __block NSInteger count = 0;        // 统计上传的数量
//    NSMutableArray *mArray = [NSMutableArray arrayWithCapacity:imgArray.count];
//    __weak typeof(self) weakSelf = self;
//    
//    self.prohander = ^(NSString *key, float percent) {
//        NSLog(@"(数组) 上传图片(%zd)进度：%.2f", count + 1, percent);
//        CGFloat actualPercent = (count + percent) / imgArray.count;
//        if (progress) {
//            NSLog(@"(数组) 总进度条：%.2f", actualPercent);
//            progress(key, actualPercent);
//        }
//    };
//    self.faiHander = ^(NSString *error) {
//        NSLog(@"(数组) 上传图片(%zd)失败：%@", count + 1, error);
//        weakSelf.isUploading = NO;
//        if (failure) {
//            failure(error);
//        }
//    };
//    self.sucHander = ^(NSArray<NSString *> *urlArray) {
//        NSLog(@"(数组) 上传图片成功：%@", urlArray);
//        [mArray addObjectsFromArray:urlArray];
//        ++count;
//        NSLog(@"(数组) 上传成功的数量=%zd, 总数量=%zd", count, imgArray.count);
//        if (count >= imgArray.count) {
//            NSLog(@"(数组) 全部图片(%zd)上传完成!", count);
//            weakSelf.isUploading = NO;
//            if (success) {
//                success(mArray);
//            }
//            return ;
//        } else {
//            NSLog(@"(数组) 开始上传图片(%zd)", count + 1);
//            if (count < imgArray.count) {
//                [weakSelf uploadSingleImage:imgArray[count]
//                                   progress:weakSelf.prohander
//                                    success:weakSelf.sucHander
//                                    failure:weakSelf.faiHander];
//            }
//        }
//    };
//    
//    [self uploadSingleImage:imgArray.firstObject
//                   progress:weakSelf.prohander
//                    success:weakSelf.sucHander
//                    failure:weakSelf.faiHander];
}

//- (void)subUploadImages:(NSArray<UIImage *> *)imgArray progress:(XDQNUpProgressHandler)progress success:(XDQNUpSuccessHandler)success failure:(XDQNUpFailureHandler)failure {
//    // 开始上传
//    self.isUploading = YES;
//    
//    // 取消上传重置为NO
//    self.cancelUploadFlag = NO;
//    
//    // 上传图片
//    __block NSInteger count = 0;        // 统计上传的数量
//    NSMutableArray *mArray = [NSMutableArray arrayWithCapacity:imgArray.count];
//    __weak typeof(self) weakSelf = self;
//    
//    self.prohander = ^(NSString *key, float percent) {
//        NSLog(@"(数组) 上传图片(%zd)进度：%.2f", count + 1, percent);
//        CGFloat actualPercent = (count + percent) / imgArray.count;
//        if (progress) {
//            NSLog(@"(数组) 总进度条：%.2f", actualPercent);
//            progress(key, actualPercent);
//        }
//    };
//    self.faiHander = ^(NSString *error) {
//        NSLog(@"(数组) 上传图片(%zd)失败：%@", count + 1, error);
//        weakSelf.isUploading = NO;
//        if (failure) {
//            failure(error);
//        }
//    };
//    self.sucHander = ^(NSArray<NSString *> *urlArray) {
//        NSLog(@"(数组) 上传图片成功：%@", urlArray);
//        [mArray addObjectsFromArray:urlArray];
//        ++count;
//        NSLog(@"(数组) 上传成功的数量=%zd, 总数量=%zd", count, imgArray.count);
//        if (count >= imgArray.count) {
//            NSLog(@"(数组) 全部图片(%zd)上传完成!", count);
//            weakSelf.isUploading = NO;
//            if (success) {
//                success(mArray);
//            }
//            return ;
//        } else {
//            NSLog(@"(数组) 开始上传图片(%zd)", count + 1);
//            if (count < imgArray.count) {
//                [weakSelf uploadSingleImage:imgArray[count]
//                                   progress:weakSelf.prohander
//                                    success:weakSelf.sucHander
//                                    failure:weakSelf.faiHander];
//            }
//        }
//    };
//    
//    [self uploadSingleImage:imgArray.firstObject
//                   progress:weakSelf.prohander
//                    success:weakSelf.sucHander
//                    failure:weakSelf.faiHander];
//}
//
//- (void)uploadSingleImage:(UIImage *)image progress:(XDQNUpProgressHandler)progress success:(XDQNUpSuccessHandler)success failure:(XDQNUpFailureHandler)failure {
//    
//    NSData *data = UIImageJPEGRepresentation(image, 0.8);
//    NSString *fileName = [self dateAndRandomStr];
//    NSLog(@"获取的名称= %@", fileName);
//    
//    QNUploadOption *option = [[QNUploadOption alloc] initWithMime:nil progressHandler:^(NSString *key, float percent) {
//        NSLog(@"(单一) 上传图片%@, 进度：%.2f", key, percent);
//        if (progress) {
//            progress(key, percent);
//        }
//    } params:nil checkCrc:NO cancellationSignal:^BOOL{
//        NSLog(@"是否取消标记：%zd", self.cancelUploadFlag);
//        return self.cancelUploadFlag;
//    }];
//    
//    [self.qnUpManager putData:data key:fileName token:self.qnUpToken complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
//        if (info.statusCode == 200 && resp) {
//            NSLog(@"(单一) 上传图片%@，dic:%@ 成功！", key, resp);
//            if (success) {
//                NSString *urlStr = [NSString stringWithFormat:@"%@/%@", KABGlobalQiNiuPrefix, resp[@"key"]];
//                success(@[urlStr]);
//            }
//        } else {
//            NSLog(@"(单一) 上传图片%@, 失败：%@", key, info.error);
//            if (failure) {
//                failure(info.error.localizedDescription);
//            }
//        }
//    } option:option];
//}

#pragma mark - 上传Data
- (void)uploadImgData:(NSArray<NSData *> *)imgDataArray progress:(XDQNUpProgressHandler)progress success:(XDQNUpSuccessHandler)success failure:(XDQNUpFailureHandler)failure {
    // 校验参数
    if (!imgDataArray.count) {
        if (failure) {
            failure(@"上传图片数组为空");
        }
        return;
    }
    
    // 判断是否真正上传
    if (self.isUploading) {
        NSLog(@"还有未完成的上传任务");
        if (failure) {
            failure(@"还有未完成的上传任务");
        }
        return;
    }
    
    // 获取上传的Token
    [self getQiniuUploadToken:^(NSString *token) {
        self.qnUpToken = token;
        [self subUploadImgData:imgDataArray progress:progress success:success failure:failure];
    } failure:^(NSString *error) {
        if (failure) {
            failure(error);
        }
    }];
}

- (void)subUploadImgData:(NSArray<NSData *> *)imgDataArray progress:(XDQNUpProgressHandler)progress success:(XDQNUpSuccessHandler)success failure:(XDQNUpFailureHandler)failure {
    // 开始上传
    self.isUploading = YES;
    
    // 取消上传重置为NO
    self.cancelUploadFlag = NO;
    
    // 上传图片
    __block NSInteger count = 0;        // 统计上传的数量
    NSMutableArray *mArray = [NSMutableArray arrayWithCapacity:imgDataArray.count];
    __weak typeof(self) weakSelf = self;
    
    self.prohander = ^(NSString *key, float percent) {
        NSLog(@"(数组) 上传图片(%zd)进度：%.2f", count + 1, percent);
        CGFloat actualPercent = (count + percent) / imgDataArray.count;
        if (progress) {
            NSLog(@"(数组) 总进度条：%.2f", actualPercent);
            progress(key, actualPercent);
        }
    };
    self.faiHander = ^(NSString *error) {
        NSLog(@"(数组) 上传图片(%zd)失败：%@", count + 1, error);
        weakSelf.isUploading = NO;
        if (failure) {
            failure(error);
        }
    };
    self.sucHander = ^(NSArray<NSString *> *urlArray) {
        NSLog(@"(数组) 上传图片成功：%@", urlArray);
        [mArray addObjectsFromArray:urlArray];
        ++count;
        NSLog(@"(数组) 上传成功的数量=%zd, 总数量=%zd", count, imgDataArray.count);
        if (count >= imgDataArray.count) {
            NSLog(@"(数组) 全部图片(%zd)上传完成!", count);
            weakSelf.isUploading = NO;
            if (success) {
                success(mArray);
            }
            return ;
        } else {
            NSLog(@"(数组) 开始上传图片(%zd)", count + 1);
            if (count < imgDataArray.count) {
                [weakSelf uploadSingleImgData:imgDataArray[count]
                                     progress:weakSelf.prohander
                                      success:weakSelf.sucHander
                                      failure:weakSelf.faiHander];
            }
        }
    };
    
    [self uploadSingleImgData:imgDataArray.firstObject
                     progress:weakSelf.prohander
                      success:weakSelf.sucHander
                      failure:weakSelf.faiHander];
}

- (void)uploadSingleImgData:(NSData *)imgData progress:(XDQNUpProgressHandler)progress success:(XDQNUpSuccessHandler)success failure:(XDQNUpFailureHandler)failure {
    
    NSString *fileName = [self dateAndRandomStr];
    NSLog(@"获取的名称= %@", fileName);
    
    QNUploadOption *option = [[QNUploadOption alloc] initWithMime:nil progressHandler:^(NSString *key, float percent) {
        NSLog(@"(单一) 上传图片%@, 进度：%.2f", key, percent);
        if (progress) {
            progress(key, percent);
        }
    } params:nil checkCrc:NO cancellationSignal:^BOOL{
        NSLog(@"是否取消标记：%zd", self.cancelUploadFlag);
        return self.cancelUploadFlag;
    }];
    
    [self.qnUpManager putData:imgData key:fileName token:self.qnUpToken complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        if (info.statusCode == 200 && resp) {
            NSLog(@"(单一) 上传图片%@，dic:%@ 成功！", key, resp);
            if (success) {
                NSString *urlStr = [NSString stringWithFormat:@"%@/%@", EFAGlobalQiNiuPrefix, resp[@"key"]];
                success(@[urlStr]);
            }
        } else {
            NSLog(@"(单一) 上传图片%@, 失败：%@", key, info.error);
            if (failure) {
                failure(info.error.localizedDescription);
            }
        }
    } option:option];
}

#pragma mark - 图片名称、Token
// 图片名称
- (NSString *)dateAndRandomStr {
    NSDate *date = [NSDate date];
    int random = arc4random() % 100;
    NSLog(@"时间戳：%f", date.timeIntervalSince1970);
    NSString * str = [NSString stringWithFormat:@"%ld_%d.jpg", (long)(date.timeIntervalSince1970 *1000), random];
    return str;
}

//获取七牛的token
- (void)getQiniuUploadToken:(void (^)(NSString * token))success failure:(void (^)(NSString * error))failure {
    // 需要先登录
    if (![EFAModel sharedInstance].isLogin) {
        NSLog(@"上传图片需要先登录");
        if (failure) {
            failure(@"上传图片需要先登录");
        }
        return;
    }
    
    // 请求Token
    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token};
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiQiniuUploadToken] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[EFAGlobalJsonKeyErrCode] integerValue] == 200) {
            if (success) {
                success(responseObject[EFAGlobalJsonKeyResult][@"upload_token"]);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"获取七牛Token失败：%@", error);
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        if (failure) {
            failure(msg);
        }
    }];
}

#pragma mark - getters and setters
- (QNUploadManager *)qnUpManager {
    if (!_qnUpManager) {
//        BOOL isHttps = TRUE;    // 支持Https
//        QNZone * httpsZone = [[QNAutoZone alloc] initWithHttps:isHttps dns:nil];
        QNConfiguration *config = [QNConfiguration build:^(QNConfigurationBuilder *builder) {
//            builder.zone = httpsZone;
            builder.useHttps = YES;
        }];
        _qnUpManager = [QNUploadManager sharedInstanceWithConfiguration:config];
    }
    return _qnUpManager;
}

@end
